package com.lawyer.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import com.lawyer.config.BaseConfigUrlBean;
import com.lawyer.model.Message;

@Component
public class TokenFilter implements Filter {

	@Autowired
	private BaseConfigUrlBean baseConfigUrlBean;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		 HttpServletResponse httpHttprespResponse = (HttpServletResponse) response;  
		 httpHttprespResponse.setHeader("Access-Control-Allow-Origin", "*");
		 httpHttprespResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
		 httpHttprespResponse.setHeader("Access-Control-Max-Age", "3600");
		 httpHttprespResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,content-type");
		 httpHttprespResponse.setHeader("Access-Control-Allow-Credentials", "true");

		String path = httpServletRequest.getServletPath();
		Message msg = new Message();
		if (path.startsWith("/swagger-ui") || path.startsWith("/swagger-resources") 
				|| path.startsWith("/webjars")
				|| path.startsWith("/v2/api-docs")
				|| path.startsWith("/lawyerFactory/login") || path.startsWith("/lawyerFactory/register")
				|| path.startsWith("/userFactory/login") || path.startsWith("/userFactory/register")
				||path.startsWith("/agent/shareGroup")
				||path.startsWith("/agent/myUserId")
				||path.startsWith("/agent/qrCodejumpUrl")
				||path.startsWith("/lawyer/recommend")
				||path.startsWith("/user/wxPayCallBlack")
				||path.startsWith("/home/queryByKeyWord")
				||path.startsWith("/call/callBlack")
				||path.startsWith("/call/callBlackFirst")
				||path.startsWith("/index.html")
				|| path.startsWith("/anli.html")
				|| path.startsWith("/fuwu.html")
				|| path.startsWith("/guanyu.html")
				|| path.startsWith("/wenzhang.html")
				||path.startsWith("/css")
				||path.startsWith("/imgs")
				|| path.startsWith("/test")
				|| path.startsWith("/system/")
				|| path.startsWith("/user/myQrCode")
				|| path.startsWith("/agentImage")
				|| path.startsWith("/selectConfig")
				|| path.startsWith("/upload")
				|| path.startsWith("/provinces")
				|| path.startsWith("/home")){
			chain.doFilter(request, response);
		} else {
			String accessToken = httpServletRequest.getHeader("access_token");
			if (StringUtils.isEmpty(accessToken)) {
				msg.setCode("400");
				msg.setMessage("请先登录");
				returnJson(response, msg);
				return;
			} else {
				try {
					String url = String.format(baseConfigUrlBean.getCheckToken(), accessToken);
					RestTemplate restTemplate = new RestTemplate();
					ResponseEntity<Object> entity = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(null), Object.class);
					if (entity.getStatusCodeValue() == 200) {
						chain.doFilter(request, response);
					}
				} catch (Exception e) {
					msg.setCode("401");
					msg.setMessage("请先登录");
					returnJson(response, msg);
					return;
				}
			}

		}

	}

	private void returnJson(ServletResponse response, Object json) {
		PrintWriter writer = null;
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=utf-8");
		JSONObject result = JSONObject.fromObject(json);
		try {
			writer = response.getWriter();
			writer.print(result + "");

		} catch (IOException e) {

		} finally {
			if (writer != null)
				writer.close();
		}
	}

}
